package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.GoodsDetailAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.GoodsAddBean;
import com.yiwei.zxp.api.bean.ParamsBean;
import com.yiwei.zxp.api.bean.UploadImgBean;
import com.yiwei.zxp.api.model.GoodsDetailModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.GoodsDetailPhotoEvent;
import com.yiwei.zxp.event.MainPacketEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.GoodsOperator;
import com.yiwei.zxp.util.ImageUtil;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ScacheUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.view.CustomParamsDilaog;
import com.yiwei.zxp.view.FullyLinearLayoutManager;
import com.yiwei.zxp.view.GoodsNumberDilaog;
import com.yiwei.zxp.view.GoodsTypeDilaog;
import com.yiwei.zxp.view.QuickServiceDilaog;
import com.yiwei.zxp.view.SelectAddressDilaog;
import com.yiwei.zxp.view.V19FrameLayout;
import com.yiwei.zxp.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class GoodsAddActivity extends BaseActivity implements SelectAddressDilaog.OnChooseListener,
        QuickServiceDilaog.OnChooseListener,
        GoodsTypeDilaog.OnChooseListener,
        CustomParamsDilaog.OnChooseListener,
        GoodsNumberDilaog.OnChooseListener {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_one)
    ImageView imgOne;
    @BindView(R.id.btn_phone_one)
    FrameLayout btnPhoneOne;
    @BindView(R.id.img_two)
    ImageView imgTwo;
    @BindView(R.id.btn_phone_two)
    FrameLayout btnPhoneTwo;
    @BindView(R.id.img_three)
    ImageView imgThree;
    @BindView(R.id.btn_phone_three)
    FrameLayout btnPhoneThree;
    @BindView(R.id.txt_good_title)
    TextView txtGoodTitle;
    @BindView(R.id.edit_title)
    EditText editTitle;
    @BindView(R.id.txt_good_money)
    TextView txtGoodMoney;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.txt_good_service)
    TextView txtGoodService;
    @BindView(R.id.edit_service)
    TextView editService;
    @BindView(R.id.layout_service)
    FrameLayout layoutService;
    @BindView(R.id.txt_good_address)
    TextView txtGoodAddress;
    @BindView(R.id.edit_address)
    TextView editAddress;
    @BindView(R.id.layout_address)
    FrameLayout layoutAddress;
    @BindView(R.id.txt_good_type)
    TextView txtGoodType;
    @BindView(R.id.edit_type)
    TextView editType;
    @BindView(R.id.layout_type)
    FrameLayout layoutType;
    @BindView(R.id.txt_good_parameter)
    TextView txtGoodParameter;
    @BindView(R.id.edit_parameter)
    TextView editParameter;
    @BindView(R.id.layout_parameter)
    FrameLayout layoutParameter;
    @BindView(R.id.layout_detail)
    FrameLayout layoutDetail;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.img_one_add)
    ImageView imgOneAdd;
    @BindView(R.id.btn_delete_one)
    ImageView btnDeleteOne;
    @BindView(R.id.btn_delete_two)
    ImageView btnDeleteTwo;
    @BindView(R.id.img_two_add)
    ImageView imgTwoAdd;
    @BindView(R.id.btn_delete_three)
    ImageView btnDeleteThree;
    @BindView(R.id.img_three_add)
    ImageView imgThreeAdd;
    @BindView(R.id.btn_detail)
    TextView btnDetail;
    @BindView(R.id.list_bottom)
    RecyclerView listBottom;
    @BindView(R.id.txt_goods_num)
    TextView txtGoodsNum;
    @BindView(R.id.edit_goods_num)
    TextView editGoodsNum;
    @BindView(R.id.layout_goods_num)
    FrameLayout layoutGoodsNum;
    private GoodsDetailAdapter bottomAdapter;
    private Unbinder unbiner;
    private String province;
    private String city;
    private String area;
    private SelectAddressDilaog selectAddressDilaog;
    private QuickServiceDilaog quickServiceDilaog;
    private CustomParamsDilaog customParamsDilaog;
    private GoodsNumberDilaog goodsNumberDilaog;
    private UploadImgAdapter uploadImgAdapter;
    private GoodsTypeDilaog goodsTypeDilaog;
    private int photo_poi = 0;
    private GoodsDetailModel.DatasBean totalData;
    //    private List<String> photos = new ArrayList<>();
    private boolean isEdit = false;
    private GoodsOperator actHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_goods);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        actHelper = new GoodsOperator(this);
        listBottom.setNestedScrollingEnabled(false);
        FullyLinearLayoutManager mLayoutManager = new FullyLinearLayoutManager(this);
        bottomAdapter = new GoodsDetailAdapter(this);
        listBottom.setLayoutManager(mLayoutManager);
        listBottom.setAdapter(bottomAdapter);
        totalData = getIntent().getParcelableExtra("data");

        txtTitle.setText("添加商品");
        selectAddressDilaog = new SelectAddressDilaog(this).setOnChooseListener(this);

        quickServiceDilaog = new QuickServiceDilaog(this).setOnChooseListener(this);

        customParamsDilaog = new CustomParamsDilaog(this).setOnChooseListener(this);

        goodsNumberDilaog = new GoodsNumberDilaog(this).setOnChooseListener(this);
        goodsTypeDilaog = new GoodsTypeDilaog(this).setOnChooseListener(this);

        if (totalData != null) {
            isEdit = true;
            initGoods(totalData);
        }


        editMoney.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                //删除.后面超过两位的数字
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editMoney.setText(s);
                        editMoney.setSelection(s.length());
                    }
                }

                //如果.在起始位置,则起始位置自动补0
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editMoney.setText(s);
                    editMoney.setSelection(2);
                }

                //如果起始位置为0并且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editMoney.setText(s.subSequence(0, 1));
                        editMoney.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }

    public void getUploadImg(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImg(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    switch (photo_poi) {
                        case 0:
                            imgOne.setImageBitmap(bitmap);
                            imgOneAdd.setVisibility(View.GONE);
                            btnDeleteOne.setVisibility(View.VISIBLE);
                            actHelper.setPhotosIndex(0, result.datas.url);
                            break;
                        case 1:
                            if (actHelper.getPhotos().size() == 0) {
                                imgOne.setImageBitmap(bitmap);
                                imgOneAdd.setVisibility(View.GONE);
                                btnDeleteOne.setVisibility(View.VISIBLE);
                            } else {
                                imgTwo.setImageBitmap(bitmap);
                                imgTwoAdd.setVisibility(View.GONE);
                                btnDeleteTwo.setVisibility(View.VISIBLE);
                            }
                            actHelper.setPhotosIndex(1, result.datas.url);
                            break;
                        case 2:
                            if (actHelper.getPhotos().size() == 0) {
                                imgOne.setImageBitmap(bitmap);
                                imgOneAdd.setVisibility(View.GONE);
                                btnDeleteOne.setVisibility(View.VISIBLE);
                            } else if (actHelper.getPhotos().size() == 1) {
                                imgTwo.setImageBitmap(bitmap);
                                imgTwoAdd.setVisibility(View.GONE);
                                btnDeleteTwo.setVisibility(View.VISIBLE);
                            } else {
                                imgThree.setImageBitmap(bitmap);
                                imgThreeAdd.setVisibility(View.GONE);
                                btnDeleteThree.setVisibility(View.VISIBLE);
                            }
                            actHelper.setPhotosIndex(2, result.datas.url);
                            break;
                    }
                });
    }

    private void initGoods(GoodsDetailModel.DatasBean item) {
        actHelper.initData(item);

        editTitle.setText(item.title);
        editMoney.setText(item.price);
        String fee = "";
        if (Float.valueOf(item.deliver_fee) == 0) {
            fee = "免运费";
        } else {
            fee = item.deliver_fee;
        }
        editService.setText(fee);
        editAddress.setText(item.province + item.city);
        editType.setText(item.cate_name);
        if (item.photos != null && item.photos.size() != 0) {
            if (item.photos.size() == 1) {
                Glide.with(this).load(item.photos.get(0)).into(imgOne);
                imgOneAdd.setVisibility(View.GONE);
                btnDeleteOne.setVisibility(View.VISIBLE);
            } else if (item.photos.size() == 2) {
                Glide.with(this).load(item.photos.get(0)).into(imgOne);
                imgOneAdd.setVisibility(View.GONE);
                btnDeleteOne.setVisibility(View.VISIBLE);
                Glide.with(this).load(item.photos.get(1)).into(imgTwo);
                imgTwoAdd.setVisibility(View.GONE);
                btnDeleteTwo.setVisibility(View.VISIBLE);
            } else if (item.photos.size() == 3) {
                Glide.with(this).load(item.photos.get(0)).into(imgOne);
                imgOneAdd.setVisibility(View.GONE);
                btnDeleteOne.setVisibility(View.VISIBLE);
                Glide.with(this).load(item.photos.get(1)).into(imgTwo);
                imgTwoAdd.setVisibility(View.GONE);
                btnDeleteTwo.setVisibility(View.VISIBLE);
                Glide.with(this).load(item.photos.get(2)).into(imgThree);
                imgThreeAdd.setVisibility(View.GONE);
                btnDeleteThree.setVisibility(View.VISIBLE);
            }
        }

        if (totalData.params != null && totalData.params.size() >= 0) {
            if (totalData.params.size() == 1) {
                editParameter.setText(totalData.params.get(0).name);
            } else {
                editParameter.setText(totalData.params.get(0).name + "...");
            }
        }
        bottomAdapter.update(totalData.details);
    }

    public void getGoodsEdit(GoodsAddBean data) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getGoodsEdit(data).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    showEditSuccessDialog();
                });
    }


    public void getGoodsAdd(GoodsAddBean data) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getGoodsAdd(data).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    showAddSuccessDialog();
                });
    }

    private void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(file);

                }
            }

            @Override
            public void callTake(File file, int mode) {

            }
        }, 0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GoodsDetailPhotoEvent event) {
//        actHelper.setPhotoDetails(event.list);
        actHelper.setDetails(event.list);
        bottomAdapter.update(event.list);
        btnDetail.setText("已上传");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ScacheUtil.clearTextLineCache();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.edit_goods_num, R.id.btn_back, R.id.btn_phone_one, R.id.btn_phone_two, R.id.btn_phone_three, R.id.edit_service, R.id.edit_address, R.id.edit_type, R.id.edit_parameter, R.id.btn_detail, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.edit_goods_num:
                goodsNumberDilaog.show();
                break;
            case R.id.btn_back:
                finishDialog();
                break;
            case R.id.btn_phone_one:
                photo_poi = 0;
                goToTakePhoto();
                break;
            case R.id.btn_phone_two:
                photo_poi = 1;
                goToTakePhoto();
                break;
            case R.id.btn_phone_three:
                photo_poi = 2;
                goToTakePhoto();
                break;
            case R.id.edit_service:
                quickServiceDilaog.show();
                break;
            case R.id.edit_address:
                selectAddressDilaog.show();
                break;
            case R.id.edit_type:
                goodsTypeDilaog.show();
                break;
            case R.id.edit_parameter:
                customParamsDilaog.show();
                break;
            case R.id.btn_detail:
                Intent intent = new Intent(this, GoodsDetailEditActivity.class);
                intent.putStringArrayListExtra("data", actHelper.getDetails());
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_submit:
                actHelper.setTitle(UI.toString(editTitle));
                actHelper.setPrice(UI.toString(editMoney));
                if (actHelper.checkInput()) {
                    if (isEdit) {
                        getGoodsEdit(actHelper.getSubmitData());
                    } else {
                        getGoodsAdd(actHelper.getSubmitData());
                    }

                }

                break;
        }
    }

    @OnClick({R.id.btn_delete_one, R.id.btn_delete_two, R.id.btn_delete_three})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.btn_delete_one:
                imgOne.setImageResource(0);
                imgOneAdd.setVisibility(View.VISIBLE);
                btnDeleteOne.setVisibility(View.GONE);
                break;
            case R.id.btn_delete_two:
                imgTwo.setImageResource(0);
                imgTwoAdd.setVisibility(View.VISIBLE);
                btnDeleteTwo.setVisibility(View.GONE);
                break;
            case R.id.btn_delete_three:
                imgThree.setImageResource(0);
                imgThreeAdd.setVisibility(View.VISIBLE);
                btnDeleteThree.setVisibility(View.GONE);
                break;
        }
    }

    private void finishDialog() {
        String tips = "";
        if (isEdit) {
            tips = "商品就快修改成功了，您确定要离开吗？";
        } else {
            tips = "就快添加商品成功了，您确定要离开吗？";
        }
        Dialog.showDefaultDialog(this, "", tips, "残忍离开", "我要留下", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {
                finish();
            }
        });
    }

    private void showEditSuccessDialog() {
        EventBus.getDefault().post(new MainPacketEvent("1"));
        Dialog.showDefaultDialog(this, "", "商品修改申请已提交请耐心等待平台审核", "", "好", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    private void showAddSuccessDialog() {
        EventBus.getDefault().post(new MainPacketEvent("1"));
        Dialog.showDefaultDialog(this, "", "商品已提交，请等待平台审核，注意消息通知", "", "好", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    @Override
    public void onBackPressed() {
        finishDialog();
    }

    @Override
    public void onQuickService(int selectPoi, String money) {
        if (selectPoi == 1) {
            editService.setText("免运费");
            actHelper.setDeliverFee("0");
        } else {
            editService.setText(money + "元");
            actHelper.setDeliverFee(money);
        }
    }

    @Override
    public void onAddressSelect(String provinceId, String provinceName, String cityId, String cityName) {
        editAddress.setText(provinceName + cityName);
        actHelper.setAddress(provinceId, cityId);
    }


    @Override
    public void onChooseType(String id, String name) {
        editType.setText(name);
        actHelper.setCateId(id);
    }

    @Override
    public void onCustomParamChoose(List<ParamsBean> data) {
        if (data.size() == 1) {
            editParameter.setText(data.get(0).name + "-" + data.get(0).value);
        } else if (data.size() > 1) {
            editParameter.setText(data.get(0).name + "-" + data.get(0).value + "...");
        }
        customParamsDilaog.setDataBean(data);
        actHelper.setParams(data);
    }

    @Override
    public void onChooseNumber(String number) {
        editGoodsNum.setText(number);
        actHelper.setGoodsNum(number);
    }
}
